<!--
 * @Descripttion: 
 * @Date: 2022-01-27 09:08:23
 * @LastEditTime: 2022-01-27 11:41:36
-->
<template>
  <div
    class="chart-container"
    ref="chart"
  >
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { fitChartSize } from '@/utils/fitChartSize'
import merge from 'lodash/merge'
export default {
  props: {
    chartOption: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    chartOption: {
      handler (val) {
        this.setOption()
      },
      deep: true
    }
  },
  components: {},
  mounted () {
    this.initChart()
    window.addEventListener('resize', this.resizeChart)
  },
  beforeDestroy () {
    if (!this.chart) return
    window.removeEventListener('resize', this.resizeChart)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    /**
     * @description: 初始化echarts实例
     */
    initChart () {
      this.chart = echarts.init(this.$refs.chart)
      this.setOption()
    },
    /**
     * @description: 渲染图表
     */
    setOption () {
      const option = {
        grid: {
          top: '8%',
          left: '8%',
          right: '8%',
          bottom: '8%'
        },
        title: {
          textStyle: {
            fontSize: fitChartSize(12)
          }
        }
      }
      const _option = merge({}, option, this.chartOption)
      this.chart && this.chart.clear()
      this.resizeChart()
      this.chart && this.chart.setOption(_option, true)
    },
    /**
     * @description: 重置图表大小
     */
    resizeChart () {
      this.chart && this.chart.resize()
    }
  }
}
</script>

<style lang='scss' scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>